'use strict';

const moment = require('moment');

exports.index = async ctx => {
  const { query } = ctx.request;
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  console.log('Cannot read property of undefined', currentUser);
  const { role, id: user } = currentUser;
  console.log('Cannot read property of undefineuser', user);
  const currentStore = await ctx.model.Store.findOne({ where: { userId: user } });
  console.log('exports.index = async ctx currentStore', currentStore);
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const { id, status, userId, newly } = query;
  console.log('controller orders index id', id);
  console.log('controller orders index status', status);
  console.log('controller orders index userId', userId);
  if (currentStore && currentStore.userId === currentUser.id) {
    where.storeId = currentStore.id;
  }
  if (id) where.id = id;
  if (userId) where.userId = userId;
  if (status) where.status = status;
  switch (role) {
    case 'member':
      where.userId = ctx.state.user.sub;
      break;
    default:

  }
  switch (newly) {
    case 'today':
      where.status = 'completed';
      where.createdAt = {
        [ctx.model.Op.between]: [ moment().startOf('day').format('YYYYMMDD'), moment().endOf('day').format('YYYYMMDD') ],
      };
      break;
    default:
  }
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'id', 'DESC' ],
    ],
    include: [
      {
        model: ctx.model.OrderItem,
      },
    ],
    where,
  };
  console.log('ctx.model.Order', options);
  const {
    count: total, rows: list,
  } = await ctx.model.Order.findAndCountAll(options);
  console.log('controller orders index list', list);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.create = async ctx => {
  ctx.validate({
    itemId: { type: 'int' },
    couponId: { type: 'int', required: false },
  });
  const { itemId, couponId } = ctx.request.body;
  console.log('orders create items', itemId);
  console.log('orders create couponId', couponId);
  const item = await ctx.model.Item.findByPk(itemId);
  const { price } = item;
  console.log('orders create price', price);
  const loginService = ctx.app.weapp.LoginService.create(ctx.request, ctx.response);
  const checkedData = await loginService.check();
  const { openId } = checkedData.userInfo;
  const { userId } = await ctx.model.WechatAccount.findByPk(openId);
  console.log('orders create userId', userId);
  const coupon = await ctx.model.Coupon.findByPk(couponId);
  console.log('orders create coupon', coupon);
  const data = {
    title: `${item.title}`,
    price,
    storeId: item.storeId,
    userId,
    amount: price,
  };
  console.log('orders create data', data);
  if (coupon && price >= coupon.require) {
    console.log('coupon && price >= coupon.require');
    data.couponId = coupon.id;
    data.discount = coupon.amount;
    data.amount -= coupon.amount;
  }
  console.log('orders create data.discount', data.discount);
  console.log('orders create data.amount', data.amount);
  const order = await ctx.model.Order.create(data);
  const orderItemData = {
    title: `${item.title}`,
    imageHash: item.imageHash,
    price,
    storeId: item.storeId,
    userId,
    itemId,
    amount: price,
  };
  await ctx.model.OrderItem.create(orderItemData);
  if (coupon && price >= coupon.require) await coupon.update({ orderId: order.id });
  console.log('orders create order', order);
  const { id: tradeId } = await order.createTrade({ price: data.amount });
  console.log('orders create tradeId', tradeId);
  const out_trade_no = String(tradeId);
  console.log('orders create ut_trade_no');
  ctx.body = await ctx.app.wechatPay.requestPayment({
    body: order.title,
    out_trade_no,
    total_fee: data.amount,
    spbill_create_ip: ctx.get('X-Real-IP'),
    trade_type: 'JSAPI',
    openid: checkedData.userInfo.openId,
  });
};

exports.update = async ctx => {
  ctx.validate({
    userStatus: { type: 'string', required: false },
  });
  const { userStatus } = ctx.request.body;
  console.log('userStatususerStatususerStatususerStatus', userStatus);
  const currentUser = await ctx.model.User.findByPk(ctx.state.user.sub);
  console.log('currentUsercurrentUsercurrentUsercurrentUser', currentUser);
  const currentStore = await ctx.model.Store.findOne({ userId: currentUser.id });
  console.log('currentStorecurrentStorecurrentStorecurrentStore', currentStore);
  const order = await ctx.model.Order.findByPk(ctx.params.id);
  console.log('orderorderorderorder', order);
  if (order) {
    if (currentStore && currentStore.userId === currentUser.id) {
      console.log('currentStore && currentStore.userId === currentUser.id');
      const newOrder = await order.update({ userStatus });
      console.log('newOrdernewOrdernewOrdernewOrder', newOrder);
      ctx.body = newOrder;
      ctx.status = 204;
    }
    if (currentUser.role === 'admin' || currentUser.role === 'facilitator') {
      ctx.body = await order.update({ userStatus });
    }
    ctx.status = 204;
  }
  ctx.status = 404;

};

exports.show = async ctx => {
  let pageSize = 10;
  const { query } = ctx.request;
  if (query.pageSize) pageSize = Number(query.pageSize);
  console.log('controller orders ctx.params.id', ctx.params.id);
  const order = await ctx.model.Order.findByPk(ctx.params.id);
  console.log('controller orders show order', order);
  if (order) {
    const orderId = order.id;
    console.log('controller orders orderId', orderId);
    const options = {
      limit: pageSize,
      offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
      where: { orderId },
    };
    console.log('controller orders options', options);
    const orderItems = await ctx.model.OrderItem.findAll(options);
    const trade = await ctx.model.Trade.findOne(options);
    console.log('controller orders show orderItems', orderItems);
    const data = { order, orderItems, trade };
    ctx.body = data;
  } else {
    ctx.status = 404;
  }
};
